package currentment.count;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.CountDownLatch;
public class AtomicCountExample {
    private static final AtomicInteger count = new AtomicInteger(0); // 共享的原子计数器
    private static final int TARGET = 10000; // 目标值
    private static final CountDownLatch latch = new CountDownLatch(1); // 用于主线程等待

    // CAS自旋
    // 它会检查当前的值是否为 currentCount，如果是，则将其更新为 currentCount + 1，并返回 true。
    // 如果当前值已经被其他线程修改，该操作会失败，返回 false。
    public static void main(String[] args) {
        Thread[] threads = new Thread[50];

        for (int i = 0; i < 50; i++) {
            threads[i] = new Thread(() -> {
                while (true) {
                    int currentCount = count.get();
                    if (currentCount >= TARGET) {
                        latch.countDown();
                        break;
                    }
                    // CAS
                    count.compareAndSet(currentCount, currentCount + 1);
                }
            });
            threads[i].start();
        }

        try {
            latch.await();
            System.out.println("Count reached "+TARGET);
        } catch (InterruptedException ignored) {
        }

        // 等待所有线程完成
        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException ignored) {

            }
        }
        System.out.println("Final count: " + count.get());
    }
}
